package com.example.demo.dao.impl;

import com.example.demo.dao.BaseDaoImpl;
import com.example.demo.dao.IEmailDao;
import com.example.demo.jooq.tables.pojos.Email;
import com.example.demo.model.po.EmailPage;
import com.example.demo.model.request.EmailPageRequest;
import com.example.demo.model.request.VpsPageRequest;
import com.example.demo.util.AssertUtils;
import com.example.demo.util.DateUtils;
import org.jooq.Condition;
import org.jooq.Record;
import org.jooq.SelectJoinStep;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

import static com.example.demo.jooq.tables.Email.EMAIL;
import static org.jooq.impl.DSL.count;

@Component
public class IEmailDaoImpl extends BaseDaoImpl implements IEmailDao {
    
    @Override
    public List<EmailPage> queryPageEmailList(EmailPageRequest emailPageRequest) {
        //查询条件
        List<Condition> conditions = new ArrayList<>();
        if(AssertUtils.isNotEmpty(emailPageRequest.getKeyword())){
            conditions.add(EMAIL.EMAIL_.likeRegex(emailPageRequest.getKeyword().trim()));
        }
        if(AssertUtils.isNotEmpty(emailPageRequest.getEmailStatus())){
            conditions.add(EMAIL.EMAIL_STATUS.eq(emailPageRequest.getEmailStatus()));
        }
        if(AssertUtils.isNotEmpty(emailPageRequest.getCreatedDate())){
            conditions.add(EMAIL.CREATED_DATE.eq(DateUtils.stringToTime(emailPageRequest.getCreatedDate())));
        }
        SelectJoinStep<Record> totalLine = this.getDslContext()
                .select(EMAIL.fields())
                .select(count().over().as("totalLine"))
                .from(EMAIL);
        totalLine.where(conditions);
        return totalLine.orderBy(EMAIL.CREATED_DATE.desc())
                .offset(emailPageRequest.getOffset())
                .limit(emailPageRequest.getPageSize())
                .fetchInto(EmailPage.class);
    }

    @Override
    public Email queryOneEmail(String email) {
        return this.getDslContext().select(EMAIL.fields()).from(EMAIL).where(EMAIL.EMAIL_.eq(email)).fetchOneInto(Email.class);
    }
}
